<?php
namespace Arathi;

use Snoopy\Snoopy;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class WeiboApi {
    private $logger;
    private $snoopy;
    private $baseUrl;

    public function __construct()
    {
        $this->logger = new Logger('WeiboApi');
        $this->logger->pushHandler(new StreamHandler('logs/api.log', Logger::DEBUG));

        $this->baseUrl = "https://api.weibo.com/2/";
        $this->snoopy = new Snoopy;
        $this->snoopy->agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 // Safari/537.36";
        $this->snoopy->httpmethod = "GET";
    }

    public function buildUrl($apiName, $params)
    {
        $url = $this->baseUrl . $apiName . ".json";
        $first = true;
        foreach ($params as $key => $value)
        {
            if ($first)
            {
                $url .= '?';
                $first = false;
            }
            else
            {
                $url .= '&';
            }
            $url .= $key . "=" . $value;
        }
        return $url;
    }
    
    public function sendGetRequest($url)
    {
        $this->logger->debug('Request: GET ' . $url);
        $this->snoopy->fetch($url);
        $json = $this->snoopy->results;
        $this->logger->debug('Response: '. $json);
        $decoded = json_decode($json);
        return $decoded;
    }

    public function statuses_public_timeline($access_token, $count=50, $page=1, $base_app=0)
    {
        $apiName = "statuses/public_timeline";
        $params = [
            'access_token' => $access_token, 
            'count' => $count,
            'page' => $page,
            'base_app' => $base_app
        ];
        $url = $this->buildUrl($apiName, $params);
        return $this->sendGetRequest($url);
    }
    
    public function statuses_home_timeline($access_token, $since_id=0, $max_id=0, $count=20, $page=1, $base_app=0, $feature=0, $trim_user=0)
    {
        $apiName = "statuses/home_timeline";
        $params = [
            'access_token' => $access_token, 
            'since_id' => $since_id, 
            'max_id' => $max_id, 
            'count' => $count, 
            'page' => $page, 
            'base_app' => $base_app, 
            'feature' => $feature, 
            'trim_user' => $trim_user
        ];
        $url = $this->buildUrl($apiName, $params);
        return $this->sendGetRequest($url);
    }
}
